package com.motong.gongdan.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.motong.gongdan.entity.Product;
import com.motong.gongdan.service.ProductService;
import com.motong.gongdan.util.LoginUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//@Configuration
@Slf4j
public class ProductRectifyInit {

    @Resource
    private ProductService productService;

    //纠正产品库存
//    @PostConstruct
    public void initProductRectify() {
//        LoginUtil.setLoginUserFactory(4);
        LoginUtil.setIgnoreFactory(true);
        Map<Integer, BigDecimal> productIdStockMap = new HashMap<>();
        productService.getBaseMapper().getProductStock().forEach(i -> productIdStockMap.put(i.getId(), i.getStock()));
        productService.getBaseMapper().getWorkReportStock().forEach(i -> {
            productIdStockMap.computeIfPresent(i.getId(), (k, v) -> i.getStock().add(v));
            productIdStockMap.putIfAbsent(i.getId(), i.getStock());
        });
        List<Product> productList = productService.list(new LambdaQueryWrapper<Product>().eq(Product::getDelFlag, 0));
        productList.forEach(i -> i.setStock(productIdStockMap.getOrDefault(i.getId(), BigDecimal.ZERO)));
        if (!CollectionUtils.isEmpty(productList)) {
            Map<Integer, List<Product>> productFactoryIdGroup = productList.stream().collect(Collectors.groupingBy(Product::getFactoryId));
            productFactoryIdGroup.forEach((k, v) -> {
                LoginUtil.setLoginUserFactory(k);
                productService.updateBatchById(productList);
                LoginUtil.setLoginUserFactory(null);
            });

        }
        LoginUtil.setLoginUserFactory(null);
    }
}
